import React, { Component, Fragment } from "react";
import { Button } from "antd";
import { Link } from "react-router-dom";
import $ from "jquery";
import { Upload, Icon, message, Tooltip } from "antd";
import "../assets/less/Human_body_search.less";
import Zmage from "react-zmage";
import { inject, observer } from "mobx-react";
import { toJS } from 'mobx'
import Checkbox_group from '../components/face_search/checkbox_group'
import {
    base64_to_str,
    str_to_base64,
    img_format_size,
} from "../utils/utils";
@inject("AdminStore")
@inject("standard_face_database_store")
@observer
export default class Rentihome extends Component {
    constructor(props) {
        super(props);
        this.state = {
            got_databases: false,//获取完成所有数据库了么
            base64_of_the_image_to_search_state: "", picture_file_state: "", uploading_state: false, body_retrieval_information_array: [], body_search_waits_for_image_to_load_icon_display_state: false, drawed: false
        };
    }
    Reset_human_body_search_all_state_data = () => {
        this.setState((prevState) => ({
            base64_of_the_image_to_search_state: "", picture_file_state: "", uploading_state: false, body_retrieval_information_array: []
        }))
    }
    clear_the_previously_drawn_diagram_fun(id) {
        var c = document.getElementById(id);
        c.height = c.height;
    }
    beforeUpload = async file => {
        if (this.state.drawed) {//清空canvas
            this.clear_the_previously_drawn_diagram_fun('canvasid')
        }
        await new Promise((resolve, reject) => {
            var fr = new FileReader();
            fr.onload = () => {
                const fileType = "image/pngimage/jpgimage/jpeg";
                if (fileType.indexOf(file.type) < 0) {
                    message.info("请上传正确的图片格式");
                    return false;
                } else if (file.size > 5 * 1024 * 1024) {
                    message.info("图片不能大于5MB");
                    return false;
                } else {
                    let picture_base64 = fr.result; // picture_base64 没有格式转化的
                    this.setState(prevState => ({
                        base64_of_the_image_to_search_state: picture_base64,
                        picture_file_state: file,
                        body_search_waits_for_image_to_load_icon_display_state: true
                    }));
                    resolve(picture_base64);
                }
            };
            fr.readAsDataURL(file);
        });
        const human_feature_extraction_results = await this.props.standard_face_database_store.HumanFeatureExtractionFun(
            file,
            this.props.AdminStore.userName,
            this.props.AdminStore.token
        );
        console.log(human_feature_extraction_results)
        const upload_the_width_and_height_of_the_picture = await this.getUploadImageWidthAndHeight(this.state.base64_of_the_image_to_search_state)
        const div_current_width_and_height = this.getDivWidthAndHeight('alternate_image_id')
        let scaling = div_current_width_and_height[0] / upload_the_width_and_height_of_the_picture[0]
        var c = document.getElementById("canvasid");
        var ctx = c.getContext("2d");
        var img = document.getElementById("alternate_image_id");
        ctx.drawImage(img, (230 - div_current_width_and_height[0]) / 2, (350 - div_current_width_and_height[1]) / 2, div_current_width_and_height[0], div_current_width_and_height[1]);
        console.log('我在画图')
        ctx.strokeStyle = '#00B9EF'
        ctx.rect(human_feature_extraction_results.body_position.l * scaling + (230 - div_current_width_and_height[0]) / 2, human_feature_extraction_results.body_position.t * scaling + (350 - div_current_width_and_height[1]) / 2, human_feature_extraction_results.body_position.w * scaling, human_feature_extraction_results.body_position.h * scaling)
        ctx.stroke();
        this.setState((prevState) => ({
            body_search_waits_for_image_to_load_icon_display_state: false,
            drawed: true
        }))
    };
    picture_lazy_load() {
        $(function () {
            lazy_load();
            // 当页面开始滚动的时候，遍历图片，如果图片出现在视窗中，就加载图片
            var clock; //函数防抖
            $('.human_body_management_ul').on('scroll', function () {
                if (clock) {
                    clearTimeout(clock);
                }
                clock = setTimeout(function () {
                    lazy_load()
                }, 200)
            });
            function lazy_load() {
                $('.human_body_management_ul .ren_ti_jian_suo_right_ul_li_img').not('[data-isLoading]').each(function () {
                    if (isShow($(this))) {
                        loadImg($(this));
                    }
                })
            }
            // 判断图片是否出现在视窗的函数
            function isShow($node) {
                if ($node.offset().top - 218 <= $('.human_body_management_ul').height()) {
                    return true
                } else {
                    return false
                }
            }
            // 加载图片的函数，就是把自定义属性data-src 存储的真正的图片地址，赋值给src
            function loadImg($img) {
                $img.css({ 'background-image': `url(${$img.attr('data-src')})` })
                // 已经加载的图片，我给它设置一个属性，值为1，作为标识
                // 弄这个的初衷是因为，每次滚动的时候，所有的图片都会遍历一遍，这样有点浪费，所以做个标识，滚动的时候只遍历哪些还没有加载的图片
                $img.attr('data-isLoading', 1);
            }
            // 一开始没有滚动的时候，出现在视窗中的图片也会加载
        })
    }
    getDivWidthAndHeight = id => {//返回数值
        let img = document.getElementById(id);
        let result = [];
        result.push(window.getComputedStyle(img).width);
        result.push(window.getComputedStyle(img).height);
        result[0] = result[0].split("px")[0];
        result[1] = result[1].split("px")[0];
        return result;
    };

    getUploadImageWidthAndHeight = url => {
        //这里返回的是一个promise
        var result = [];
        var p = new Promise(function (resolve, reject) {
            var img = new Image();
            img.src = url;
            img.onload = function () {
                result[0] = img.width;
                result[1] = img.height;
                resolve(result);
            };
        });
        return p;
    };

    human_feature_library_search_elements = async () => {//开始搜索函数
        if (this.props.standard_face_database_store.checkedList <= 0) {
            message.info('请选择搜索范围')
        } else {
            let no_people_found = 0
            let body_retrieval_information_array = []
            this.setState(prevState => ({
                uploading_state: true
            }));
            //1.上传的图片中是否有人脸
            const catch_people = await this.props.standard_face_database_store.HumanFeatureExtractionFun(
                this.state.picture_file_state
            );
            console.log(catch_people)
            //2.HumanFeatureExtractionFun
            if (catch_people.condition === 'success') {
                console.log(toJS(this.props.standard_face_database_store.checkedList))
                for (let [index, database] of this.props.standard_face_database_store.checkedList.entries()) {
                    const human_feature_library_search_element_results = await this.props.standard_face_database_store.human_feature_library_search_elements(
                        catch_people.feature_vector,
                        database,
                        this.props.AdminStore.token
                    );
                    console.log(human_feature_library_search_element_results)
                    if (human_feature_library_search_element_results.result === 'no_people_found') {
                        no_people_found += 1
                    } else {

                        for (let [index, item] of human_feature_library_search_element_results.information_array.entries()) {
                            body_retrieval_information_array.push({
                                for_appear_img: str_to_base64(base64_to_str(database) + base64_to_str(item['fnd-id'])), searchScore: item.score, user: base64_to_str(item['fnd-id'])
                            })
                        }
                    }
                }
            } else {
                this.Reset_human_body_search_all_state_data()
                message.info('未抓取到人体，请更换图片')
            }
            //最后处理结果
            if (no_people_found === this.props.standard_face_database_store.checkedList.length) {
                $(function () {
                    $('.human_body_management_ul').append(' <div class="no_data_class"><div class="no_data_word">暂无数据</div></div>')
                })
            } else {
                function compare(key) {//属性搜索比较
                    return function (value1, value2) {
                        var val1 = value1[key];
                        var val2 = value2[key];
                        return val2 - val1;
                    }
                }
                body_retrieval_information_array.sort(compare('searchScore'));
                this.setState((prevState) => ({
                    body_retrieval_information_array: body_retrieval_information_array
                }), () => {
                    this.picture_lazy_load()
                })
            }
        }

    };
    componentDidMount = async () => {
        window.scrollTo(0, 0);
        await this.props.standard_face_database_store.get_face_database(this.props.AdminStore.token); //获取所有的特征库
        this.setState((prevState) => ({
            got_databases: true
        }))
        console.log(toJS(this.props.standard_face_database_store.newFaceStoreList))
    };
    render() {
        return (
            <Fragment>
                <div className="ren_ti_jian_suo_wrapper">
                    <div className="ren_ti_jian_suo_left">
                        <div className="ren_ti_jian_suo_left_content_wrap">
                            <div className="ren_ti_jian_suo_left_content_wrap_top_decoration">
                                <div className="ren_ti_jian_suo_left_content_wrap_top_decoration_describe">
                                    上传图片
                                </div>
                            </div>
                            <div className="ren_ti_jian_suo_left_content_wrap_top_line"></div>
                            <div className="ren_ti_jian_suo_left_content_wrap_top_container">
                                <Upload.Dragger beforeUpload={this.beforeUpload}>
                                    {this.state.base64_of_the_image_to_search_state ? (
                                        <React.Fragment>
                                            <Icon type="loading" style={{ display: this.state.body_search_waits_for_image_to_load_icon_display_state ? 'block' : 'none' }} className="human_body_retrieval_waiting_for_image_loading_icon_class_name" />
                                            <canvas id="canvasid" width="230px"
                                                height="350px" className="ren_ti_jian_suo_left_content_wrap_top_container_img">
                                            </canvas>
                                            <img src={this.state.base64_of_the_image_to_search_state} id="alternate_image_id" alt="" />
                                        </React.Fragment>
                                    ) : (
                                            <React.Fragment>
                                                <div className="ren_ti_jian_suo_left_content_wrap_top_container_plus"></div>
                                                <div className="ren_ti_jian_suo_left_content_wrap_top_container_describe">
                                                    选择图片
                                                </div>
                                            </React.Fragment>
                                        )}
                                </Upload.Dragger>
                            </div>
                            <Button
                                className="ren_ti_jian_suo_left_content_wrap_top_button search_button_class"
                                id="search_btn_1"
                                onMouseEnter={() => {
                                    $("#search_btn_1").css("background", "#007CDC");
                                }}
                                onMouseLeave={() => {
                                    $("#search_btn_1").css("background", "#00A3FF");
                                }}
                                style={{

                                }}
                                onClick={async () => {
                                    this.setState((prevState) => ({
                                        body_retrieval_information_array: []//重置数据
                                    }))
                                    $((function () {
                                        $('.no_data_class').remove()
                                    }))
                                    await this.human_feature_library_search_elements()
                                    this.setState(prevState => ({
                                        uploading_state: false
                                    }));
                                }}
                                loading={this.state.uploading_state}
                            >
                                {this.state.uploading_state ? "搜索中" : "搜索"}
                                {/* 搜索按钮 */}
                            </Button>
                        </div>
                        <div className="searchs">
                            <div className="search_scope">搜索范围</div>
                            <div className="checkbox_group">
                                {
                                    this.state.got_databases && <Checkbox_group />
                                }
                            </div>
                        </div>

                    </div>
                    <div className="ren_ti_jian_suo_right">
                        <div className="human_body_management_ul human_search_ul_height">
                            {this.state.body_retrieval_information_array.map((item, index) => {
                                return (
                                    <li key={index}>
                                        <div className="similarity_class_name">{item.searchScore}%</div>
                                        <div className="ren_ti_jian_suo_right_ul_li_img_wrap">
                                            <a
                                                onClick={() =>
                                                    Zmage.browsing({//修改这行代码记得下面还有一行和这个一模一样的
                                                        src: "/face/v1/image/store/" + item.for_appear_img
                                                    })
                                                }
                                            >
                                                <div
                                                    onClick={() => {
                                                        let that = this
                                                        $(function () {
                                                            $("#zmageImage").replaceWith(`<div class="imageLayer__33OvN" id="zmageImage" 
                                  style="background:url('/face/v1/image/store/${item.for_appear_img}');visibility: visible"
                                ></div>`);
                                                            $('#zmageBackground').append('<div class="delete_icon_class"></div>')
                                                        })
                                                    }}
                                                    style={{
                                                        background: item.for_appear_img
                                                    }}
                                                    data-src={`/face/v1/image/store/` + item.for_appear_img}
                                                    className="ren_ti_jian_suo_right_ul_li_img"
                                                ></div>

                                            </a>
                                            <div>
                                                {}
                                            </div>
                                        </div>

                                        <div className="ren_ti_jian_suo_right_ul_li_people_icon_name_wrap">
                                            <div className="ren_ti_jian_suo_right_ul_li_people_icon"></div>
                                            <div className="ren_ti_jian_suo_right_ul_li_people_name">
                                                <Tooltip title={(item.user)}>
                                                    <span>
                                                        {(item.user).length > 7
                                                            ? (item.user).substring(
                                                                0,
                                                                7
                                                            ) + "..."
                                                            : (item.user)}
                                                    </span>
                                                </Tooltip>
                                            </div>
                                        </div>
                                    </li>
                                );
                            })}
                        </div>
                    </div>
                </div>
            </Fragment>
        );
    }
}
